#!/usr/bin/env bash
set -e -x

{{ lxc_cache_prep_pre_commands }}

{% include 'templates/prep-scripts/_container_sys_setup.sh.j2' %}

# We have (tried to!) copied repo-oss and repo-update from the host so wipe everything else.
find /etc/zypp/repos.d/ -type f ! -name "repo-oss.repo" -a ! -name "repo-update.repo" -delete
zypper lr | grep -q 'repo-oss' || zypper --quiet ar {{ lxc_hosts_opensuse_mirror_url }}/distribution/leap/{{ lxc_cache_map.release }}/repo/oss repo-oss
zypper lr | grep -q 'repo-update' || zypper --quiet ar {{ lxc_hosts_opensuse_mirror_url }}/update/leap/{{ lxc_cache_map.release }}/oss repo-update

# Disable recommended packages. Only update what's really needed
if ! fgrep -qx "solver.onlyRequires = true" /etc/zypp/zypp.conf; then
    echo -e "\n\n## Disable recommended packages\nsolver.onlyRequires = true" >> /etc/zypp/zypp.conf
fi

# Update base distribution
zypper --gpg-auto-import-keys -n dup --force-resolution -l
zypper --gpg-auto-import-keys -n in --force-resolution -l {{ lxc_cache_distro_packages | join(' ') }}
mkdir -p /var/backup
chage -I -1 -d -1 -m 0 -M 99999 -E -1 root

# NOTE(hwoarang): Enable sshd which has been explicitely disabled in
# https://github.com/lxc/lxc-ci/commit/8dc7105399350a59698538a12b6d5a1a880ef2ba
if systemctl list-unit-files sshd.service | egrep '(masked|disabled)'; then
  systemctl -q unmask sshd
  systemctl -q enable sshd
fi

rm /etc/machine-id || true
rm /var/lib/dbus/machine-id || true
touch /etc/machine-id
rm /etc/sysctl.d/* || true
echo '' > /etc/sysctl.conf
for action in disable mask; do
  systemctl ${action} wicked.service || true
  systemctl ${action} wickedd.service || true
  systemctl ${action} wickedd-auto4.service || true
  systemctl ${action} wickedd-dhcp4.service || true
  systemctl ${action} wickedd-dhcp6.service || true
  systemctl ${action} wickedd-nanny.service || true
done

# Set the IP of the lxcbr0 interface as the DNS server
echo "nameserver {{ lxc_net_address }}" > /etc/resolv.conf
systemctl enable systemd-networkd
{{ lxc_cache_prep_post_commands }}
